﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace MVCExtension.FrameWork
{
    public static class JsonHelper
    {  //将对象序列化为字符串
        public static string Jso_ToJSON(this object tem_obj)
        {
            JavaScriptSerializer tem_serializer = new JavaScriptSerializer();
            return tem_serializer.Serialize(tem_obj);
        }


        //将字符串反序列化为对象
        public static T Jso_DeJSON<T>(this string json)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(json);
        }

        public static string Obj2Json<T>(T data)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, data);
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// 转换为ExtGrid需要的Store格式
        /// totalCount，data
        /// </summary>
        /// <param name="totalCount"></param>
        /// <param name="DT"></param>
        /// <returns></returns>
        public static string ExtGridFormatJosn(int totalCount, object DT)
        {

            string strJsonSource = @"{""totalCount"":""" + totalCount + "";
            strJsonSource = strJsonSource + @""",""data"":" + Jso_ToJSON(DT) + "}";
            return strJsonSource;
        }


    }

    public static class FormatJsonExtension
    {
        public static FormatJsonResult JsonFormat(this Controller c, object data)
        {
             return new FormatJsonResult { Data=data};
        }

        
    }

    public class FormatJsonResult : ViewResult
    {
        
        public Object Data { get; set; }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/json";

           
           response.Write(JsonHelper.Obj2Json(Data));
        }
    }

}